package com.woniuxy.microcurrentserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.bean.BillBean;
import com.woniuxy.bean.ResultBean;
import com.woniuxy.bean.current.OutOrderBean;
import com.woniuxy.bean.current.PageInfos;
import com.woniuxy.microcurrentserver.entity.CurrentFundInfo;
import com.woniuxy.bean.current.MemberCurrentAccount;
import com.woniuxy.microcurrentserver.feign.PayFeign;
import com.woniuxy.microcurrentserver.service.CurrentFundInfoService;
import com.woniuxy.microcurrentserver.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 活期基金订单控制类
 */
@RefreshScope
@Slf4j
@Api("活期支付与订单生成")
@RestController
@RequestMapping(value = "currentOrderInfo", produces = MediaType.APPLICATION_JSON_VALUE)
public class OrderController {


    @Resource
    private OrderService orderService;

    @Resource
    private CurrentFundInfoService currentFundInfoService;

    @Resource
    private PayFeign payFeign;

    /**
     * class:
     * create by: 陈酒
     * description:支付并建立订单
     * create time: 2021/4/15
     *
     * @param: pageInfos
     */
    @ApiOperation("支付与建立订单")
    @PostMapping("createOrder")
    public ResultBean createOrder (@RequestBody PageInfos pageInfos) {
        BillBean billBean = new BillBean();
        billBean.setModifiedPrice(Double.parseDouble(pageInfos.getFundNum()));
        billBean.setProductType("活期");
        billBean.setProductId(pageInfos.getId());
        billBean.setMemberName(pageInfos.getName());
        billBean.setProductName(pageInfos.getProductName());
        billBean.setPayPassword(pageInfos.getPayPassword());
        billBean.setPayType(pageInfos.getPayType());
        if (pageInfos.getBankCardId()!=null) {
            billBean.setBankCardId(pageInfos.getBankCardId());
        }
        if (billBean.getModifiedPrice() > 0) {
            billBean.setOrderType("购买");
        } else {
            billBean.setOrderType("赎回");
        }
        ResultBean s = payFeign.balancePayment(billBean);
        //支付是否成功
        //支付成功 更新订单
        if (s.getCode() == 200) {
            //确认是否已有收益列表
            MemberCurrentAccount memberCurrentAccount = orderService.checkMember(pageInfos.getCode(), pageInfos.getName());

            boolean b = true;
            Double d = new Double(Math.abs(billBean.getModifiedPrice().doubleValue()));
            if (billBean.getModifiedPrice()<0&&d>Double.parseDouble(memberCurrentAccount.getOverAllBalance())){
                return ResultBean.builder().msg("订单更新失败,赎回金额大于持有金额").code(905).build();
            }
            //如果有列表则更新购入金额和总价值
            if (memberCurrentAccount!=null) {
                int u = orderService.updateFundNum(pageInfos);
            } else {
                //添加活期收益列表
                b = orderService.insertOrder(pageInfos);

            }
            if (! b) {
                return ResultBean.builder().msg("订单更新失败").code(905).build();
            }
            MemberCurrentAccount memberCurrentAccount2 = orderService.checkMember(pageInfos.getCode(), pageInfos.getName());
            if (Double.parseDouble(memberCurrentAccount2.getFundNum())<0){
                orderService.setFundNumZero(pageInfos.getCode(), pageInfos.getName());
            }
            return ResultBean.builder().msg("订单生成功").code(200).build();
        }
        else {
            return s;
        }
    }

    /**
     * class:
     * create by: 陈酒
     * description:获得活期收益信息
     * create time: 2021/4/15
     *
     * @param:
     */
    @ApiOperation("获得用户活期信息")
    @PostMapping("getUserCurrentInfo")
    public ResultBean getUserCurrentInfo (@ApiParam("只需要传用户名userName")@RequestBody PageInfos pageInfos) {

        //查询活期累计收益
        List<MemberCurrentAccount> list = orderService.getUserCurrentInfo(pageInfos.getUserName());

        if (list == null || list.size() < 1) {
            return ResultBean.builder().code(200).msg("该用户暂时未购买任何活期产品").build();
        }

        Set<String> codes = new HashSet<>();
        for (MemberCurrentAccount a:list
             ) {
            codes.add(a.getCurrentCode());
        }
        List<CurrentFundInfo> currentFundInfos = currentFundInfoService.queryFundByCodeSet(codes);
        HashMap<String, CurrentFundInfo> currentFundInfoHashMap = new HashMap<>();
        for (CurrentFundInfo a: currentFundInfos
             ) {
           currentFundInfoHashMap.put(a.getCode(),a);
        }
        //计算所有产品的总收益
        double sumEarning = 0.0;
        //总价值
        double sumOverAllBalance = 0.0;
        //当日总收益
        double todaySumEarning = 0.0;

        for (MemberCurrentAccount regularEarning : list) {
            sumEarning += Double.parseDouble(regularEarning.getTotalEarnings());
            sumOverAllBalance += Double.parseDouble(regularEarning.getOverAllBalance());
            todaySumEarning += Double.parseDouble(regularEarning.getTodayEarnings());
            if (regularEarning.getCurrentCode()!=null&&currentFundInfoHashMap.get(regularEarning.getCurrentCode())!=null) {
                regularEarning.setCodeName(currentFundInfoHashMap.get(regularEarning.getCurrentCode()).getName());
                regularEarning.setMillionCopiesIncome(currentFundInfoHashMap.get(regularEarning.getCurrentCode()).getMillionCopiesIncome());
                regularEarning.setHoldingGains(Double.parseDouble(regularEarning.getOverAllBalance())-Double.parseDouble(regularEarning.getFundNum()));
                regularEarning.setHoldingEarnings((Double.parseDouble(regularEarning.getOverAllBalance())-Double.parseDouble(regularEarning.getFundNum()))/Double.parseDouble(regularEarning.getFundNum()));
            }
        }
        OutOrderBean outOrderBean = new OutOrderBean(sumEarning,sumOverAllBalance, todaySumEarning,list );

        return ResultBean.builder().msg("获取成功").code(200).data(outOrderBean).build();
    }


}
